const express = require("express");
const router = express.Router();

const path = require("path");
const xlsx = require("node-xlsx");

const upload = require("../../middle/multer/importFile");

const fs = require("fs");

const studentDB = require("../../schemas/student.js");
const importDB = require("../../schemas/import.js");

const iconvLite = require("iconv-lite");

// 返回模板
router.get("/template", async (req, res) => {
  res.download(path.join(__dirname, "../../dist/excel/模板.xlsx"), (err) => {
    if (err) throw err;
  });
});

// 导入文件
router.post("/student", upload.single("file"), (req, res) => {
  const arr = xlsx.parse(req.file.path)[0].data.filter((item) => item.length);

  // property用于筛选出 中文属性 替换为 英文属性
  const property = {
    手机号: "phoneNumber",
    课程分类: "kindName",
    课程名称: "courseName",
    班期名称: "className",
    是否开通权限: "isEnable",
    姓名: "name",
    微信: "wechat",
    身份证号: "card",
    年龄: "age",
    地址: "location",
    学历: "education",
    性别: "sex",
    QQ: "QQ",
  };

  let newArr = arr[0].map((item) => {
    item = item.replace("*", "");
    return property[item];
  });
  // console.log("newArr", newArr);

  // 数据的主体
  let result = arr.slice(1);
  // console.log("result", result);
  let total = result.length;
  if (!total) {
    return res.send({
      code: 1,
      txt: "空表无数据",
    });
  }

  // 有数据继续往下走.
  // 格式化student对象
  let resultStudent = [];

  for (let i = 0; i < result.length; i++) {
    let student = {};

    for (let j = 0; j < newArr.length; j++) {
      if (newArr[j] === "isEnable") {
        student[newArr[j]] = result[i][j] === "是" ? true : false;
      } else {
        student[newArr[j]] = result[i][j];
      }
    }
    resultStudent.push(student);
  }
  // console.log(resultStudent);

  // 记录不符合规范的 student对象 以及数据库以及数据库添加失败的student对象
  let errorStudent = [];

  // 符合规范的student
  let successStudent = [];

  // 记录数据库真正添加成功的student
  let succeedStudent = [];

  let reg = /^(\d{11})$/;

  let courseObj = JSON.parse(
    fs.readFileSync(path.join(__dirname, "../../dataJson/courseObj.json"))
  );

  // console.log(courseObj);
  for (let k = 0; k < resultStudent.length; k++) {
    // 对里面每一个对象进行规则筛选
    if (
      !resultStudent[k].phoneNumber &&
      !resultStudent[k].kindName &&
      !resultStudent[k].courseName &&
      !resultStudent[k].className
    ) {
      // 如果每个项目都为空
      return res.send({
        code: 2,
        txt: "表格格式不对，请按照模板要求填写",
      });
    }
    if (
      !resultStudent[k].phoneNumber ||
      !resultStudent[k].kindName ||
      !resultStudent[k].courseName ||
      !resultStudent[k].className
    ) {
      // 只要一个为空就进来
      resultStudent[k].reason = "缺少必填项";
      errorStudent.push(resultStudent[k]);
      // 跳过当前循环
      continue;
    }

    // 不符合规则
    if (!reg.test(resultStudent[k].phoneNumber)) {
      resultStudent[k].reason = "手机号不符合规范";
      errorStudent.push(resultStudent[k]);
      // 跳过当前循环
      continue;
    }

    const kindNameIndex = courseObj.kindName.findIndex((item) => {
      return resultStudent[k].kindName === item.value;
    });

    if (kindNameIndex === -1) {
      // 分类不符合规则
      resultStudent[k].reason = "项目分类不符合规则";
      errorStudent.push(resultStudent[k]);
      // 跳过当前循环
      continue;
    }

    const courseNameArr = courseObj.kindName[kindNameIndex].courseName;

    const courseNameIndex = courseNameArr.findIndex((item) => {
      return resultStudent[k].courseName === item.value;
    });
    if (kindNameIndex === -1) {
      // 课程不符合规范
      resultStudent[k].reason = "课程不在指定的分类中";
      errorStudent.push(resultStudent[k]);
      continue;
    }

    const classNameArr = courseNameArr[courseNameIndex].className;
    const classNameIndex = classNameArr.findIndex((item) => {
      return resultStudent[k].className === item;
    });
    if (classNameIndex === -1) {
      // 班期不在指定的课程中
      resultStudent[k].reason = "班期名称不在指定的课程中";
      errorStudent.push(resultStudent[k]);
      continue;
    }

    successStudent.push(resultStudent[k]);
  }
  // 存数据库
  function addStudent() {
    const promiseAll = [];
    // successStudent 2
    successStudent.forEach((item) => {
      promiseAll.push(
        new Promise((resolve, reject) => {
          studentDB
            .create({
              phoneNumber: item.phoneNumber,
              kindName: item.kindName,
              courseName: item.courseName,
              className: item.className,
              origin: "后台导入",
              updatePeople: "猪猪侠",
              updateTime: Date.now(),
              isEnable: item.isEnable,
              info: {
                phoneNumber: item.phoneNumber,
                name: item.name,
                wechat: item.wechat,
                QQ: item.QQ,
                card: item.card,
                age: item.age,
                location: item.location,
                education: item.education,
                sex: item.sex,
              },
            })
            .then(() => {
              // 数据上传成功
              succeedStudent.push(item);
              resolve();
            })
            .catch(() => {
              item.reason = "手机号重复";
              errorStudent.push(item);
              resolve();
            });
        })
      );
    });
    return Promise.all(promiseAll);
  }
  addStudent().then(() => {
    let filename = iconvLite.decode(req.file.originalname, "utf8");
    console.log(filename);

    let status;
    let succeedNum = succeedStudent.length;
    let errNum = errorStudent.length;
    if (!succeedNum) {
      //成功数组内没有数据
      // 全部失败
      status = 2;
    } else if (!errNum) {
      //失败数组内没有数据  ！0=>true
      status = 0;
    } else {
      // 部分成功
      status = 1;
    }
    let txt = `成功上传了${succeedNum}条数据，失败${errNum}条数据`;

    importDB.create({
      // 文件名
      filename,
      importPeople: "猪猪侠",
      status,
      total,
      succeedNum,
      errNum,
      errorStudent,
      succeedStudent,
      time: Date.now(),
    });
    res.send({ code: status, txt });
  });
});

// 返回导入列表
router.get("/importList", async (req, res) => {
  const { currentPage, pageSize } = req.query;
  let data = await importDB.find();

  data.sort((a, b) => {
    return b.time - a.time;
  });

  // 总数
  const total = data.length;

  // 返回splice切下来的数组
  data = data.splice((currentPage - 1) * pageSize, pageSize);

  res.send({
    code: 0,
    data,
    total
  })
});

module.exports = router;
